﻿//    Copyright (C) Kherty.  All rights reserved.
using OpenLS.Core.Serialization;

namespace OpenLS.Spreadsheet
{
    public class AboveAverageFormattingRule : StandardConditionalFormattingRule
    {
        internal override ConditionalFormattingType Type
        {
            get { return ConditionalFormattingType.AboveAverage; }
        }
        internal override bool Apply(Cell cell)
        {
            return ApplyStyle(cell, appliesTo(cell));
        }
        protected override void ReadInner2(ReadContext context)
        {
            AboveAverage = context.GetOptionalBoolean("aboveAverage", true);
                
        }
        internal override void PrepareBeforeWrite(ConditionalFormatting conditionalFormatting, ConditionalFormattingRule.FormatType formatType)
        {
            if (formatType == FormatType.Biff)
            {
                Formula1 = string.Format("=SUM({0})=0", conditionalFormatting.Range.TopLeftCell.Label); ///\\\
            }
        }
        internal override void WriteInner2(WriteContext context)
        {
            context.SetOptionalBoolean("aboveAverage", AboveAverage, true);

        }

        private bool _aboveAverage = true;

        public bool AboveAverage
        {
            get { return _aboveAverage; }
            set { _aboveAverage = value; NotifyPropertyChanged("AboveAverage");}
        }
        bool appliesTo(Cell cell)
        {
            object o = cell.Value;
            if (!(o is double))
            {
                return false;
            }
            var n = (double) o;
            if (AboveAverage)
            return n > _average;
            return n < _average;
        }
        internal override void ApplyRange(Range range)
        {
            double total = 0;
            int count = 0;
            foreach (var cell in Enumerable.Where(range.GetNonEmptyCells(), c => c.Value is double))
            {
                count++;
                total += (double) cell.Value;
            }
            _average = total/count;
        }

        private double _average;
    }
}
